package naming

import (
	"errors"
	"flag"
	"go-main/library/conf/dsn"
	"google.golang.org/grpc"
	"os"
)

var (
	discUrl string

	ErrNoAppId = errors.New("lost appId")
)

func init() {
	flag.StringVar(&discUrl, "disc_url", os.Getenv("DISC_URL"), `discovery url of server.`)
}

type config struct {
	Network   string `dsn:"network"`
	Address   string `dsn:"address"`
	Namespace string `dsn:"query.namespace"`
	//AppID     string `dsn:"query.appid"`
	//Timeout xtime.Duration `dsn:"query.timeout"`
}

// IName Register an instance and renew automatically
type IName interface {
	RegisterInstance(string) error
	RegisterResolver() grpc.DialOption
	Close() error
}

func RegisterInstance(appId string) error {
	d, err := dsn.Parse(discUrl)
	if err != nil {
		return err
	}
	var c config
	if _, err = d.Bind(&c); err != nil {
		return err
	}

	switch c.Network {
	case "nacos":
		return NewNacos(&c).RegisterInstance(appId)
	}
	return nil
}

func RegisterResolver() grpc.DialOption {
	d, err := dsn.Parse(discUrl)
	if err != nil {
		return nil
	}
	var c config
	if _, err = d.Bind(&c); err != nil {
		return nil
	}

	switch c.Network {
	case "nacos":
		x := NewNacos(&c).RegisterResolver()
		return x
	}
	return nil
}
